package org.goyo.main.web.controller.sale;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.goyo.common.baseBean.AjaxResult;
import org.goyo.common.baseBean.Constants;
import org.goyo.common.utils.DateUtils;
import org.goyo.common.utils.JSONUtil;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.entity.sale.SaleOrder;
import org.goyo.main.domain.entity.sale.SaleOrderEntry;
import org.goyo.main.domain.entity.system.SysDepGroup;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.sale.ISaleOrderService;
import org.goyo.main.web.controller.BaseController;
import org.goyo.main.web.controller.system.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
 * 销售订单
 * 
 * @author chenchuan
 * 2014年11月12日
 */
@Controller
@RequestMapping("/saleOrder")
public class SaleOrderController extends BaseController  {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource
	private ISaleOrderService saleOrderService;
	
	/**
	 * 列表界面
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/toSaleOrderList")
	public String toSaleOrderList(){
		logger.info("----------------------");
		return "/sale/SaleOrderList";
	}
	
	/**
	 * 保存或者更新
	 * 6
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/saveOrUpdateSaleOrder")
	@ResponseBody
	public AjaxResult saveOrUpdateSaleOrder(HttpServletRequest request){
		
		AjaxResult result = null;
		try{
			String form = request.getParameter("formData");
			String delData = request.getParameter("delData");
			SaleOrder saleOrder = JSONUtil.json2Obj(form, SaleOrder.class);
			Object[] delUuids = null;
			if(delData != null &&!"null".equals(delData) &&!"undefined".equals(delData)){
				JSONArray delArray = JSONArray.fromObject(delData);
				List<SaleOrderEntry> delEntry = JSONArray.toList(delArray, SaleOrderEntry.class);
				delUuids = ToolUtils.getFiles(delEntry,"uuid").toArray();
			}
			SaleOrder info = saleOrderService.saveOrUpdateInfo(saleOrder, delUuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("保存成功", info);
		}catch(Exception e){
			result = AjaxResult.resultFail("保存失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 提交数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/submitSaleOrder")
	@ResponseBody
	public AjaxResult submitSaleOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<SaleOrder> list = (List<SaleOrder>)JSONArray.toCollection(jsonarray, SaleOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			SaleOrder info  = saleOrderService.submitByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("提交成功", info);
		}catch(Exception e){
			result = AjaxResult.resultFail("提交失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 审核数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/auditSaleOrder")
	@ResponseBody
	public AjaxResult auditSaleOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<SaleOrder> list = (List<SaleOrder>)JSONArray.toCollection(jsonarray, SaleOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			SaleOrder info = saleOrderService.auditByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("审核成功", info);
		}catch(Exception e){
			result = AjaxResult.resultFail("审核失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 反审核数据
	 * 
	 * @author chenchuan
	 * 2014年11月16日
	 */
	@RequestMapping("/unAuditSaleOrder")
	@ResponseBody
	public AjaxResult unAuditSaleOrder(HttpServletRequest request){
		AjaxResult result = null;
		Object[] uuids = null;
		
		String rows = request.getParameter("rows");
		try{
			if(rows != null && !"".equals(rows)){
				JSONArray jsonarray = JSONArray.fromObject(rows);
				List<SaleOrder> list = (List<SaleOrder>)JSONArray.toCollection(jsonarray, SaleOrder.class);
				uuids = ToolUtils.getFiles(list, "uuid").toArray();
			}else{
				String uuid = request.getParameter("uuid");
				uuids = new Object[]{uuid};
			}
			SaleOrder info = saleOrderService.unAuditByUuids(uuids,getCurrentUser());
			info.setEntrys(null);
			result = AjaxResult.resultSuccess("反审核成功", info);
		}catch(Exception e){
			result = AjaxResult.resultFail("反审核失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	
	/**
	 * 删除
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/delSaleOrder")
	@ResponseBody
	public AjaxResult delSaleOrder(HttpServletRequest request){
		AjaxResult result = null;
		String rows = request.getParameter("rows");
		try{
			JSONArray jsonarray = JSONArray.fromObject(rows);
//			List<SaleOrder> list = (List<SaleOrder>)JSONArray.toCollection(jsonarray, SaleOrder.class);
			saleOrderService.delByUuids(jsonarray.toArray());
			result = AjaxResult.resultSuccess("删除成功", null);
		}catch(Exception e){
			result = AjaxResult.resultFail("删除失败", null);
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	/**
	 * 查看
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/viewSaleOrder")
	public String viewSaleOrder(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		SaleOrder info = null;
		try {
			info = saleOrderService.findByUuuid(uuid);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		model.addAttribute("info", JSONObject.fromObject(info, jsonConfig));
		model.addAttribute("editStatus", Constants.VIEW);
		return "/sale/SaleOrderEdit";
	}
	
	/**
	 * 修改
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/alterSaleOrder")
	public String alterSaleOrder(HttpServletRequest request,Model model){
		String uuid = request.getParameter("uuid");
		SaleOrder info = null;
		try {
			info = saleOrderService.findByUuuid(uuid);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		model.addAttribute("info", JSONObject.fromObject(info, jsonConfig));
		model.addAttribute("editStatus", Constants.EDIT);
		return "/sale/SaleOrderEdit";
	}
	
	/**
	 * 添加
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/addSaleOrder")
	public String addSaleOrder(HttpServletRequest request,Model model){
		SaleOrder info = new SaleOrder();
		//获取登陆用户
		SysUser user = (SysUser) SessionUtil.getAttribute("user");
		info.setCreateDate(DateUtils.getCurrentDate());
		info.setCreateUser(user);
		info.setAlterDate(DateUtils.getCurrentDate());
		info.setAlterUser(user);
		info.setStatus(Constants.NEWSTATUS);
		info.setNumber(getBillNumber(SaleOrder.BIZTYPE));
		info.setDepGroup(user.getDepGroup());
		info.setDeliveryWay("fayun");
		info.setSalePerson(user);
		model.addAttribute("info",JSONUtil.obj2Json(info));
		model.addAttribute("editStatus", Constants.NEW);
		return "/sale/SaleOrderEdit";
	}
	
	
	@RequestMapping("/listEntryData")
	@ResponseBody
	public String listEntryData(HttpServletRequest request){
		JSONObject data = null;
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		String deliveryWay = request.getParameter("deliveryWay");
		StringBuffer where = new StringBuffer(request.getParameter("where") == null ? "" : request.getParameter("where") + " and");
		if(deliveryWay != null && !"".equals(deliveryWay)){
			where.append(" saleOrder.deliveryWay = '"+ deliveryWay +"'");
			where.append(" and saleOrder.status = '4'");

		}
		
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		try {
			pager = saleOrderService.findByEntryCond(where.toString(), pager);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			data =JSONObject.fromObject(map, jsonConfig);
			
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();

	}
	
	/**
	 * list列表数据加载
	 * 
	 * @author chenchuan
	 * 2014年11月9日
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public String ListData(HttpServletRequest request){
		JSONObject data = null;
		//分页条件
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("pagesize"));
		String sortname = request.getParameter("sortname");
		String sortorder = request.getParameter("sortorder");
		
		String where = request.getParameter("where"); 
		//分页器
		Pager pager = Pager.convert(page, pageSize, sortname, sortorder);
		
		//当前登录用户
		SysUser user = getCurrentUser();
		List<SysDepGroup> groups = getUserDepGroup(user);
		Object[] groupUuids = ToolUtils.getFiles(groups,"uuid") == null ? null : ToolUtils.getFiles(groups,"uuid").toArray();
		try {
			pager = saleOrderService.findByCondition(where, pager,groupUuids);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("Rows", pager.getList());
			map.put("Total", pager.getCount());
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
			data = JSONObject.fromObject(map,jsonConfig);
		}catch (Exception e) {
			logger.error(e.getMessage(),e);
		} 
		return data.toString();
	}
	
	/**
	 * 导入
	 * @author chenchuan
	 * 2014年12月18日
	 */
	@RequestMapping("/importExcel")
	@ResponseBody
	public AjaxResult importExcel(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String billNumber = getBillNumber(SaleOrder.BIZTYPE);
		try{
			MultipartFile maltipartFile = multipartRequest.getFile("excelFile");
			saleOrderService.importExcel(maltipartFile,	getCurrentUser(),billNumber);
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			return AjaxResult.resultFail("导入失败", null);
		}
		return AjaxResult.resultSuccess("导入成功", null);
	}
	
	/**
	 * 导出
	 * @author chenchuan
	 * 2014年12月22日
	 */
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request,HttpServletResponse response){
		OutputStream ouputStream = null;
		ByteArrayOutputStream os = null;
		
		String where = request.getParameter("where"); 
		//分页器
		Pager pager = new Pager<SaleOrder>();
		
		//当前登录用户
		SysUser user = getCurrentUser();
		List<SysDepGroup> groups = getUserDepGroup(user);
		Object[] groupUuids = ToolUtils.getFiles(groups,"uuid") == null ? null : ToolUtils.getFiles(groups,"uuid").toArray();
		try {
			pager = saleOrderService.findByCondition(where, pager,groupUuids);
			pager.getList();
			
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("sheet1");
		    sheet.autoSizeColumn(1, true);
			HSSFRow headRow = sheet.createRow(0);
			headRow.createCell(0).setCellValue(1);
			
			os = new ByteArrayOutputStream();  
			wb.write(os);  
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			// 设置编码
			response.setCharacterEncoding("ISO-8859-1");
			response.reset();
//			// 写明要下载的文件的大小
			response.setContentLength(os.toByteArray().length);
			// 发送到客户端的文章
			String filename = new String("test".getBytes(), "ISO-8859-1");
//			response.setHeader("Content-Disposition", "attachment;filename="
//					+ filename);
			response.setBufferSize(2048);
			response.setContentType("application/vnd.ms-excel");  
	        response.setHeader("Content-disposition", "attachment;filename="+filename+".xls");  
	        ouputStream = response.getOutputStream();  
	        wb.write(ouputStream);  
	        ouputStream.flush();  
			
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
	}
}
